<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络聊天室</title>
</head>
<style>
    #contains{
        background-color: pink;
        width: 1000px;
        height: 700px;
        margin: auto;
    }
    #username{
        background-color: powderblue;
        width: 1000px;
        height: 30px;
    }
    #new{
        background-color: rgb(5, 130, 146);
        width: 1000px;
        height: 30px;
    }
    #left{
        background-color: salmon;
        width: 700px;
        height: 640px;
        float: left;
        position: relative;
    }
    #content{
        background-color: silver;
        width: 700px;
        height: 400px;
        /*display: none;*/
        /*visibility: hidden;*/
    }
    #right{
        background-color: rgb(107, 3, 3);
        width: 300px;
        height: 640px;
        float: right;
    }
    #hylist{
        height: 270px;
        overflow-y: scroll;
        background: antiquewhite;
    }
    #xtlist{
        height: 270px;
        overflow-y: scroll;
        background: antiquewhite;
    }
    #input{
        margin-bottom: 0px;
        position: absolute;
        bottom: 0px;
    }
    #mes_left{
        float: left;
        border: 2px aqua;
        max-width: 490px;
    }
    #mes_right{
        float: right;
        border: 2px aqua;
        max-width: 490px;
    }
    #hy{
        display: block;
        width: 300px;
    }
    textarea {
        resize: none;
        border: none;
        outline: none
    }
</style>
<body>
<div id = "contains">
    <div id="username"><h3 style="text-align: center;">用户：张三<span>-在线</span></h3></div>
    <div id="new"></div>
    <div id="left">
        <div id="content">
        </div>
        <div id="input">
            <input type="text" id="input_text" style="width: 695px;height: 200px;">
            <button id="submit" style="float: right;">发送</button>
        </div>
    </div>
    <div id="right">
        <p id="hy" style="text-align: center;">好友列表</p>
        <div id="hylist">

        </div>
        <p id="xt" style="text-align: center">系统消息</p>
        <div id="xtlist">

        </div>
    </div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    var username;
    var toName;
    function showChat(name){
        // alert("dsaad");
        toName = name;
        //清空聊天区
        $("#content").html("");
        //显示"正在和谁聊天"
        $("#new").html("当前正与"+toName+"聊天");
        //sessionStorage
        var chatData = localStorage.getItem(toName);
        if (chatData != null){
            //将聊天记录渲染到聊天区
            $("#content").html(chatData);
        }

        //是否有离线消息
    }

    $(function () {
        $.ajax({
            url:"getUsername",
            success:function (res) {
                username = res;
                $("#username").html("用户："+ username +"<span>在线</span>");
                // $("#username").html("用户：123<span>在线</span>");
            },
            async:false //同步请求，只有上面好了才会接着下面
        });

        //创建webSocket对象
        var ws = new WebSocket("ws://localhost:9000/chat");
        //给ws绑定事件，建立socket连接
        ws.onopen = function (ev) {
            //在建立连接后，显示在线用户信息
            $("#username").html("用户："+ username +"<span>在线</span>");
        }
        //接受服务端推送的消息后触发
        ws.onmessage = function (ev) {
            //获取服务端推送过来的消息
            var datastr = ev.data;
            //将datastr转换为 json对象
            var res = JSON.parse(datastr);
            //判断是否是系统消息
            if(res.system){
                //1.好友列表
                //2.系统广播
                var names = res.message;
                var userlistStr = ""; //好友列表
                var broadcastListStr = ""; //系统广播

                for (var name of names){
                    if (name != username){
                        userlistStr += "<a onclick='showChat(\""+name+"\")'>"+ name +"</a></br>";
                        broadcastListStr += "<p>"+ name +"上线了</p>";
                    }
                };
                //渲染好友列表和系统广播
                $("#hylist").html(userlistStr);
                $("#xtlist").html(broadcastListStr);

            }else {
                //不是系统消息
                //将服务端推送的消息进行展示
                var str = "<span id='mes_left'>"+ res.message +"</span></br>";
                //
                if (toName == res.fromName) {
                    $("#content").append(str);
                }

                var chatdata = localStorage.getItem(res.fromName);
                if (chatdata != null){
                    str = chatdata + str;
                }
                localStorage.setItem(res.fromName,str);

            }
        }

        ws.onclose = function (ev) {
            //关闭socket连接，显示离线用户信息
            $("#username").html("用户："+ username +"<span>离线</span>");
        }

        //发送消息
        $("#submit").click(function () {
            //获取输入的内容
            var data = $("#input_text").val();
            //清空输入区的内容
            $("#input_text").val("");
            var json = {"toName": toName ,"message": data};
            //将数据展示在聊天区
            var str = "<span id='mes_right'>"+ data +"</span></br>";
            $("#content").append(str);

            //
            var chatData = localStorage.getItem(toName);
            if (chatData != null){
                str = chatData + str;
            }
            localStorage.setItem(toName,str);
            //发送数据给服务端
            ws.send(JSON.stringify(json));
        });
    })
</script>
<script src="https://eqcn.ajz.miesnfu.com/wp-content/plugins/wp-3d-pony/live2dw/lib/L2Dwidget.min.js"></script>
<!--小帅哥： https://unpkg.com/live2d-widget-model-chitose@1.0.5/assets/chitose.model.json-->
<!--萌娘：https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json-->
<!--小可爱（女）：https://unpkg.com/live2d-widget-model-koharu@1.0.5/assets/koharu.model.json-->
<!--小可爱（男）：https://unpkg.com/live2d-widget-model-haruto@1.0.5/assets/haruto.model.json-->
<!--初音：https://unpkg.com/live2d-widget-model-miku@1.0.5/assets/miku.model.json-->
<!-- 上边的不同链接显示的是不同的小人，这个可以根据需要来选择 下边的初始化部分，可以修改宽高来修改小人的大小，或者是鼠标移动到小人上的透明度，也可以修改小人在页面出现的位置。 -->
<script>
    /*https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json*/
    L2Dwidget.init({ "model": { jsonPath:
                "https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json",
            "scale": 1 }, "display": { "position": "right", "width": 110, "height": 150,
            "hOffset": 0, "vOffset": -20 }, "mobile": { "show": true, "scale": 0.5 },
        "react": { "opacityDefault": 0.8, "opacityOnHover": 0.1 } });
</script>
</html>